package com.h.extensions.listener;

import com.h.extensions.constant.Constants;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;

@Component
public class DLListener {
    // 监听 普通信息的队列，如果出现错误的话，信息发送到 死信队列中
    @RabbitListener(queues = Constants.NORMAL_QUEUE)
    public void handMessage(Message message, Channel channel) throws IOException {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            //消费者逻辑
            System.out.printf("[normal.queue]接收到消息: %s, deliveryTag: %d /n",
                    new String(message.getBody(),"UTF-8"), deliveryTag);

            // 消费者进行业务处理
            System.out.println("业务逻辑处理");
            int sum = 3/0;
            System.out.println("业务逻辑处理");
            // 业务处理成功，肯定确认
            channel.basicAck(deliveryTag, false);
        }catch (Exception e) {
            // 否定确认
            channel.basicNack(deliveryTag, false, false); //requeue为false, 该消息成为死信
        }
    }

    @RabbitListener(queues = Constants.DL_QUEUE)
    public void handMessage(Message message) throws UnsupportedEncodingException {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        //消费者逻辑
        System.out.printf("[dl.queue] %tc 接收到消息: %s, deliveryTag: %d \n", new Date(),
                new String(message.getBody(),"UTF-8"), deliveryTag);
    }
}
